package com.ming.listener;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.ming.config.WxMsgAutoConfiguration;
import com.ming.config.WxMsgProperties;
import com.ming.constant.QueueConstant;
import com.ming.model.WxMsgModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 * @Author:何元才
 * @Desc: 发送微信公众号消息的监听
 * @data:2021-04-07 21:08
 */
@Component
@Slf4j
public class WxMsgListener {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private WxMsgProperties wxMsgProperties;

    @Autowired
    private WxMsgAutoConfiguration wxMsgAutoConfiguration;

    /**
     * 这个是监听微信公众号消息的方法
     * @param message
     * @param channel
     */
    @RabbitListener(queues = QueueConstant.WX_SMS_QUEUE, concurrency = "3-5")
    public void wxMsgHandler(Message message, Channel channel){
        log.info("有人发消息进来了");
        // 处理 restTemplate.postForObject(url,msg,String.class);
        // 1.拿到消息
        String wxStr = new String(message.getBody());
        WxMsgModel wxMsgModel = JSON.parseObject(wxStr, WxMsgModel.class);
        //2.发送
        try {
            realWxSend(wxMsgModel);
            //3.记录数据库
            //4.签收
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            log.error("发送失败");
        }
    }

    /**
     * 真正发送消息的方法
     *
     * @param wxMsgModel
     */
    private void realWxSend(WxMsgModel wxMsgModel) {
        String sendMsgUrl = wxMsgProperties.getSendMsgUrl();
        String wxToken = wxMsgAutoConfiguration.getWX_TOKEN();
        String sendUrl = String.format(sendMsgUrl, wxToken);
        String result = restTemplate.postForObject(sendUrl, wxMsgModel, String.class);
        System.out.println(result);
    }


}
